package com.yksj.healthtalk.ui.interestwall;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.SearchAdapter;
import com.yksj.healthtalk.adapter.SearchAdapter.onCheckChangeSendListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.BaseInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.HStringUtil;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 转发 列表
 * @author jack_tang
 *
 */
@SuppressLint("NewApi")
public class ForwardListActivity extends BaseFragmentActivity implements OnClickListener, OnCheckedChangeListener, onCheckChangeSendListener {

	private int type;// 放入smartfox内的标志位 话题2,好友1
	private ListView refreshableView;
	private SearchAdapter<BaseInfoEntity> mAdapter;
	private CheckBox mIsSelectAllCheck;
	private PullToRefreshListView mRefreshListView;
	private int sendState;
	final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			showLodingDialog.dismissAllowingStateLoss();
			if ("y".equalsIgnoreCase(intent.getStringExtra("FLAG"))) {
				ToastUtil.showShort(getApplicationContext(), "转发成功");
				sendState=1;
				// 好友转发消息需要保存到本地
				if (type == 1) {
					Message message = mHandler.obtainMessage();
					message.obj = new MessageEntity[] {(MessageEntity) intent.getSerializableExtra("picture"),
							(MessageEntity) intent.getSerializableExtra("text") };
					message.what = 1;
					mHandler.sendMessage(message);
				}
				requestHttpSendStatus();
				onBackPressed();
			} else {
				ToastUtil.showShort(getApplicationContext(), "转发失败");
				sendState=0;
			}
		};
	};

	protected void requestHttpSendStatus() {
		HttpRestClient.doHttpActionForImage(getIntent().getStringExtra("picID"), SmartFoxClient.getLoginUserId(),String.valueOf(0) , null);
	}
	
	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 保存消息到数据库
			if (msg.what == 1) {
				final MessageEntity[] entities = (MessageEntity[]) msg.obj;
				new Thread() {
					public void run() {
						ChatUserHelper helper = ChatUserHelper.getInstance();
						List<String> list = mAdapter.getSelectIDs();
						if (entities[0] != null) {
							MessageEntity entity = entities[0];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
						if (entities[1] != null) {
							MessageEntity entity = entities[1];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
					};
				}.start();
			}
		}
	};
	private LodingFragmentDialog showLodingDialog;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.forward_list_layout);
		initView();
	}

	private void initView() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText(getIntent().getStringExtra("title"));
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setText("确定");
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleTextV.setText(getIntent().getStringExtra("title"));
		mIsSelectAllCheck = (CheckBox) findViewById(android.R.id.checkbox);
		mIsSelectAllCheck.setOnCheckedChangeListener(this);
		mRefreshListView = (PullToRefreshListView) findViewById(android.R.id.list);
		
		TextView emptyView = new TextView(this);   
		emptyView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));   
		emptyView.setText("暂无数据");  
		emptyView.setTextSize(16);
		emptyView.setVisibility(View.GONE);   
		emptyView.setGravity(Gravity.CENTER);
		mRefreshListView.setEmptyView(emptyView);  
		
		refreshableView = mRefreshListView.getRefreshableView();
		refreshableView.addFooterView(getLayoutInflater().inflate(R.layout.line_layout,null));
		
		List<BaseInfoEntity> entities=new ArrayList<BaseInfoEntity>();
		mAdapter = new SearchAdapter<BaseInfoEntity>(this, entities,true);
		mAdapter.setType(1);
		mAdapter.setOnChooseCheckListener(this);
		
		refreshableView.setAdapter(mAdapter);
		mRefreshListView.setRefreshing();
		type=getIntent().getIntExtra("tag", 1);
		initData();
	}

	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(mReceiver);
	}

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter(MessagePushService.ACTION_REPEAT_STATE);
		registerReceiver(mReceiver, filter);
	}
	
	private void initData() {
		RequestParams params=new RequestParams();
		params.put("CUSTOMERID", SmartFoxClient.getLoginUserId());
		params.put("OPTION", getIntent().getStringExtra("OPTION"));
		params.put("TYPE", getIntent().getStringExtra("TYPE"));//MYATTENTION
		HttpRestClient.doHttpInterestForwardNum(params, new ObjectHttpResponseHandler() {
			@Override
			public Object onParseResponse(String content) {
				try {
					JSONObject object=new JSONObject(content);
					if(type==1){//朋友
						return FriendHttpUtil.jsonAnalysisFriendEntity(object.optJSONArray("INFO").toString(), false);
					}else{//沙龙
						return SalonHttpUtil.jsonAnalysisSalonEntity(ForwardListActivity.this,object.optJSONArray("INFO").toString());
					}
				} catch (JSONException e) {
					return null;
				}
			}
			@Override
			public void onSuccess(int statusCode, Object response) {
				super.onSuccess(statusCode, response);
				if(response!=null && response instanceof ArrayList){
					List<BaseInfoEntity> entities=(List<BaseInfoEntity>) response;
					if(entities==null||entities.size()==0)
					findViewById(android.R.id.widget_frame).setVisibility(View.GONE);
					else
					mAdapter.addListEntity(entities);
				}else{
					findViewById(android.R.id.widget_frame).setVisibility(View.GONE);
				}
			}
			@Override
			public void onFinish() {
				super.onFinish();
				mRefreshListView.onRefreshComplete();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2://转发
			try {
				
				String picID = getIntent().getStringExtra("picID");
				if(mIsSelectAllCheck.isChecked()){//转发全部
					showLodingDialog = LodingFragmentDialog.showLodingDialog(getSupportFragmentManager(), getResources());
					JSONObject object=new JSONObject();
					object.put(getIntent().getStringExtra("flag"), getIntent().getStringExtra("flag"));
					SmartFoxClient.sendRepeatToAll(object.toString(), picID);
				}else if(!HStringUtil.isEmpty(mAdapter.getCusIds())){//非全部
					showLodingDialog = LodingFragmentDialog.showLodingDialog(getSupportFragmentManager(), getResources());
					SmartFoxClient.sendRepeatToFriend(String.valueOf(type),mAdapter.getCusIds(),String.valueOf(picID) );
				}else{
					ToastUtil.showToastPanl("未选择话题");
				}	
			} catch (Exception e) {
			}
			break;
		}
	}

	/**
	 * 是否全选 回调
	 */
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if(isChecked){
			mAdapter.selectAll();
		}else{
			mAdapter.clearSelectAll();
		}
	}

	/**
	 * 点击item中的check
	 * @param isCheck
	 * @param position
	 */
	@Override
	public void onChooseCheckChange(boolean isCheck, int position) {
		if(!isCheck){
			mIsSelectAllCheck.setOnCheckedChangeListener(null);
			mIsSelectAllCheck.setChecked(false);
			mIsSelectAllCheck.setOnCheckedChangeListener(this);
		}
	}
	
}
